package com.guanyong.webapi.controllers.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.guanyong.model.*;
import com.guanyong.services.*;
import com.guanyong.utils.Comm.AlipayConfig;
import com.guanyong.utils.Comm.DateExt;
import com.guanyong.utils.Comm.ResultCode;
import com.guanyong.utils.Comm.ResultObject;
import com.guanyong.utils.UniqueID.DBObjectID;
import com.guanyong.utils.UniqueID.LoginTokenID;
import com.guanyong.webapi.handle.UserHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2017/7/5 0005.
 */
@RestController
@RequestMapping("/api/videopay/")
public class VideoPayApi {

    @Autowired
    AliPayLogService aliPayLogService;

    @Autowired
    FilmServices filmServices;
    @Autowired
    PriceTagService priceTagService;


    @Autowired
    UserBaseService userBaseService;

    @Autowired
    VideoBuyLogServices videoBuyLogServices;

    @RequestMapping(value = "notify", method = RequestMethod.POST)
    public String notify(HttpServletRequest request) throws Exception {
        ResultObject<Integer> resultObject = new ResultObject<Integer>();
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号

        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

        System.out.println("--------------11111111111111");



        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");

            Set keSet=requestParams.entrySet();
            for(Iterator itr=keSet.iterator();itr.hasNext();){
                Map.Entry me=(Map.Entry)itr.next();
                Object ok=me.getKey();
                Object ov=me.getValue();
                String[] value=new String[1];
                if(ov instanceof String[]){
                    value=(String[])ov;
                }else{
                    value[0]=ov.toString();
                }

                for(int k=0;k<value.length;k++){
                    System.out.println(ok+"="+value[k]);
                }
            }



            AliPayLogModel aliPayLogModel = new AliPayLogModel();
            aliPayLogModel.setPayId(new DBObjectID().toString());
            aliPayLogModel.setNotifyId(new String(request.getParameter("notify_id").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setAppId(new String(request.getParameter("app_id").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setSign(new String(request.getParameter("sign").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setTradeNo(new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setOutTradeNo(new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setBuyerId(new String(request.getParameter("buyer_id").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setBuyerLogonId(new String(request.getParameter("buyer_logon_id").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setSellerId(new String(request.getParameter("seller_id").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setSellerEmail(new String(request.getParameter("seller_email").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setTradeStatus(new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8"));
            Double totalAmount =Double.valueOf( new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8"));
            BigDecimal b   =   new   BigDecimal(totalAmount);
            aliPayLogModel.setTotalAmount(b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
            Double receiptAmount =Double.valueOf( new String(request.getParameter("receipt_amount").getBytes("ISO-8859-1"),"UTF-8"));
            b   =   new   BigDecimal(receiptAmount);
            aliPayLogModel.setReceiptAmount(b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
            Double buyerPayAmount =Double.valueOf( new String(request.getParameter("buyer_pay_amount").getBytes("ISO-8859-1"),"UTF-8"));
            b   =   new   BigDecimal(buyerPayAmount);
            aliPayLogModel.setBuyerPayAmount(b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
            aliPayLogModel.setBody(new String(request.getParameter("body").getBytes("ISO-8859-1"),"UTF-8"));
            Date gmtCreate = DateExt.StrToDate(new String(request.getParameter("gmt_create").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setGmtCreate(gmtCreate);
            Date gmtPayment = DateExt.StrToDate(new String(request.getParameter("gmt_payment").getBytes("ISO-8859-1"),"UTF-8"));
            aliPayLogModel.setGmtPayment(gmtPayment);
            aliPayLogModel.setPassbackParams(new String(request.getParameter("passback_params").getBytes("ISO-8859-1"),"UTF-8"));
            int res = aliPayLogService.AddAliPayLog(aliPayLogModel);

            if(verify_result){//验证成功
                System.out.println("--------------验证成功");
                //////////////////////////////////////////////////////////////////////////////////////////
                //请在这里加上商户的业务逻辑程序代码

                //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

                if(trade_status.equals("TRADE_FINISHED")){
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。



                } else if (trade_status.equals("TRADE_SUCCESS")){
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
                    String[] temp = aliPayLogModel.getPassbackParams().split(",");
                    if (temp.length==3){
                        String token = temp[0];
                        String objectid = temp[1];
                        Integer appType = Integer.valueOf(temp[2]);

                        LoginTokenID ltID = new LoginTokenID(token);
                        UserBaseModel userBaseModel =userBaseService.getUserModel(ltID.getUid(),1);
                        FilmModel filmModel=filmServices.GetFilmModelById(objectid);
                        VideoBuyLogModel videoBuyLogModel = new VideoBuyLogModel();
                        PriceTagModel priceTagModel =priceTagService.GetPriceTagById(filmModel.getfPricetagid());

                        if (userBaseModel != null && !userBaseModel.getfId().equals("")) {
                            if (filmModel != null ) {
                                if (!(filmModel.getfPricetagid().equals("0"))&&priceTagModel!=null){
                                    int amount =  new Double(aliPayLogModel.getTotalAmount()*100).intValue() ;
                                    int money =new Double(priceTagModel.getfMoney()*100).intValue() ;
                                    if (amount!=money){
                                        aliPayLogService.ErrorPay(aliPayLogModel.getPayId(),"价格错误");
                                    }else{
                                        String newid = new DBObjectID().toString();
                                        videoBuyLogModel.setfId(newid);
                                        videoBuyLogModel.setfBillid(aliPayLogModel.getNotifyId());
                                        videoBuyLogModel.setfBilltype(0);
                                        videoBuyLogModel.setfBillname(aliPayLogModel.getBody());
                                        videoBuyLogModel.setfUserid(userBaseModel.getfId());
                                        videoBuyLogModel.setfClasstype(1);
                                        videoBuyLogModel.setfApptype(appType);
                                        videoBuyLogModel.setfObjectid(filmModel.getfId());
                                        videoBuyLogModel.setfMoney(aliPayLogModel.getTotalAmount());
                                        videoBuyLogModel.setfIntime(new Date());
                                        Date fOffday = new Date(new Date().getTime()+(priceTagModel.getfOffday()+1)* 24 * 60 * 60 * 1000);
                                        videoBuyLogModel.setfOffday(fOffday);
                                        videoBuyLogModel.setfState(1);
                                        videoBuyLogServices.AddBuyLog(videoBuyLogModel);
                                    }
                                }else{
                                    aliPayLogService.ErrorPay(aliPayLogModel.getPayId(),"没有价格标签");
                                }
                            }else {
                                aliPayLogService.ErrorPay(aliPayLogModel.getPayId(),"电影不存在");
                            }


                        }else {
                            aliPayLogService.ErrorPay(aliPayLogModel.getPayId(),"用户登录失败");
                        }

                    }else {
                        aliPayLogService.ErrorPay(aliPayLogModel.getPayId(),"前端参数错误");
                    }
                }

                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
                //            response.println("success");	//请不要修改或删除
                return "success";
                //////////////////////////////////////////////////////////////////////////////////////////
            }else{//验证失败
                System.out.println("--------------验证失败");
                return "fail";
                //            response.println("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "success";
    }
}
